package com.taotao.rest.service.ipml;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.rest.dao.IJedisClient;
import com.taotao.rest.service.IContentService;

/**
 * 内容管理业务层
 * 
 * @author Administrator
 *
 */
@Service
public class ContentServiceIpml implements IContentService {
	@Autowired
	private TbContentMapper contentMapper;

	@Autowired
	private IJedisClient jedisClient;

	@Value(value = "${INDEX_CONTENT_REDIS_KEY}")
	private String INDEX_CONTENT_REDIS_KEY;

	@Override
	public TaotaoResult getContentLlst(Long categoryId) {
		// 从redis中获取数据
		try {
			String result = this.jedisClient.hget(INDEX_CONTENT_REDIS_KEY,
					categoryId + "");
			if (StringUtils.isNotBlank(result)) {
				return JsonUtils.jsonToPojo(result, TaotaoResult.class);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		TbContentExample example = new TbContentExample();
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(categoryId);
		// 通过内容分类id执行查询
		List<TbContent> contents = this.contentMapper.selectByExample(example);
		// 向redis 中添加数据
		try {
			TaotaoResult taotaoResult = TaotaoResult.ok(contents);
			String jsonStr = JsonUtils.objectToJson(taotaoResult);
			this.jedisClient.hset(INDEX_CONTENT_REDIS_KEY, categoryId + "",
					jsonStr);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return TaotaoResult.ok(contents);
	}
}
